<template>
  <div class="question-bank-manager">
    <h1>题库管理</h1>
    <el-button type="primary" @click="handleAddQuestion" style="margin-bottom: 20px;">添加题目</el-button>

    <div v-if="questions.length" class="question-list">
      <h2>题目列表</h2>
      <el-card v-for="(question, index) in questions" :key="question.questionId" class="question-item">
        <div slot="header">
          <span>{{ question.title }} - {{ getTestTypeName(question.test_type) }}</span>
          <el-button-group style="float: right;">
            <el-button size="small" type="warning" @click="handleUpdateQuestion(question)">更新</el-button>
            <el-button size="small" type="danger" @click="deleteQuestion(question.questionId)">删除</el-button>
          </el-button-group>
        </div>
        <p><strong>选项:</strong></p>
        <ul>
          <li v-for="option in question.optionList" :key="option.optionId">
            {{ option.optionId }}: {{ option.content }}
          </li>
        </ul>
        <p><strong>答案:</strong> {{ question.answer }}</p>
        <p><strong>解释:</strong> {{ question.explain }}</p>
      </el-card>
    </div>

    <!-- 新增题目对话框 -->
    <el-dialog title="新增题目" :visible.sync="dialogVisible" width="50%">
      <el-form :model="currentQuestion" label-width="100px">
        <el-form-item label="题目标题">
          <el-input v-model="currentQuestion.title"></el-input>
        </el-form-item>
        <el-form-item label="题目类型">
          <el-select v-model="currentQuestion.test_type" placeholder="请选择题目类型">
            <el-option label="单选" value="1"></el-option>
            <el-option label="多选" value="2"></el-option>
            <el-option label="判断" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选项">
          <el-table :data="currentQuestion.optionList" border style="width: 100%">
            <el-table-column prop="optionId" label="选项ID" width="80"></el-table-column>
            <el-table-column prop="content" label="内容">
              <template slot-scope="scope">
                <el-input v-model="scope.row.content"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button size="mini" @click="removeOption(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="text" @click="addOption">添加选项</el-button>
        </el-form-item>
        <el-form-item label="答案">
          <el-input v-model="currentQuestion.answer"></el-input>
        </el-form-item>
        <el-form-item label="解释">
          <el-input v-model="currentQuestion.explain" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="分类ID">
          <el-input v-model="currentQuestion.categoryId"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchQuestions, addNewQuestion, updateQuestion, deleteQuestion } from '@/common/api';

export default {
  data() {
    return {
      questions: [],
      dialogVisible: false,
      currentQuestion: {
        questionId: null,
        title: "",
        test_type: "1",
        optionList: [
          { optionId: "A", content: "" },
          { optionId: "B", content: "" }
        ],
        answer: "",
        explain: "",
        categoryId: ""
      },
      isEditing: false
    };
  },
  created() {
    this.fetchQuestions();
  },
  methods: {
    async fetchQuestions() {
      try {
        const response = await fetchQuestions();
        this.questions = response.data;
        console.log('获取到的题目列表:', this.questions);
      } catch (error) {
        console.error('获取题目失败:', error);
      }
    },
    handleAddQuestion() {
      this.isEditing = false;
      this.currentQuestion = {
        questionId: null,
        title: "",
        test_type: "1",
        optionList: [
          { optionId: "A", content: "" },
          { optionId: "B", content: "" }
        ],
        answer: "",
        explain: "",
        categoryId: ""
      };
      this.dialogVisible = true;
    },
    handleUpdateQuestion(question) {
      this.isEditing = true;
      this.currentQuestion = JSON.parse(JSON.stringify(question));
      this.dialogVisible = true;
    },
    submitForm() {
      if (this.isEditing) {
        this.updateQuestion(this.currentQuestion);
      } else {
        this.addNewQuestion(this.currentQuestion);
      }
      this.dialogVisible = false;
    },
    async addNewQuestion(newQuestion) {
      try {
        await addNewQuestion(newQuestion);
        this.fetchQuestions(); // 重新获取题目列表
      } catch (error) {
        console.error('添加题目失败:', error);
      }
    },
    async updateQuestion(updatedQuestion) {
      try {
        await updateQuestion(updatedQuestion.questionId, updatedQuestion);
        this.fetchQuestions(); // 重新获取题目列表
      } catch (error) {
        console.error('更新题目失败:', error);
      }
    },
    async deleteQuestion(questionId) {
      console.log('正在删除题目ID:', questionId); // 添加调试信息
      if (!questionId && questionId !== 0) {
        console.error('题目ID无效');
        return;
      }
      try {
        await deleteQuestion(questionId);
        this.fetchQuestions(); // 重新获取题目列表
      } catch (error) {
        console.error('删除题目失败:', error);
      }
    },
    getTestTypeName(testType) {
      switch (testType) {
        case "1":
          return "单选";
        case "2":
          return "多选";
        case "3":
          return "判断";
        default:
          return "未知类型";
      }
    },
    addOption() {
      const newOptionId = String.fromCharCode(65 + this.currentQuestion.optionList.length); // A, B, C, ...
      this.currentQuestion.optionList.push({ optionId: newOptionId, content: "" });
    },
    removeOption(index) {
      this.currentQuestion.optionList.splice(index, 1);
    }
  }
};
</script>

<style scoped>
.question-bank-manager {
  padding: 20px;
  background-color: #f9f9f9;
}

h1 {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

h2 {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.el-button {
  margin-right: 10px;
}

.question-list {
  margin-top: 20px;
}

.question-item {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.question-item .el-button-group {
  margin-top: 10px;
}

.question-item p {
  font-size: 14px;
  color: #666;
}

.question-item ul {
  padding-left: 20px;
}

.question-item li {
  list-style-type: disc;
  margin-bottom: 8px;
}

.el-dialog {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-form-item label {
  font-weight: bold;
}

.el-table {
  margin-bottom: 10px;
}

.el-table-column {
  text-align: center;
}

.el-input {
  width: 100%;
}

.el-button[type="primary"] {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button[type="primary"]:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.el-button[type="danger"] {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.el-button[type="danger"]:hover {
  background-color: #f78989;
  border-color: #f78989;
}

.el-select {
  width: 100%;
}

.el-input[type="textarea"] {
  resize: none;
  min-height: 100px;
}

.el-form-item label {
  color: #666;
}
</style>
